package mvc.spring.controller;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import mvc.spring.controller.commandObject.UserRegistationCommand;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import domain.User;

import DAO.IUserDAO;

@Controller
public class RegistrationController {

	private static Logger log = Logger.getLogger(RegistrationController.class);
	
	@Autowired
	private IUserDAO userDao; 
	
	@RequestMapping(method=RequestMethod.GET, value="/registration")
	public String registration(Model model, 
								HttpServletRequest request,
								HttpServletResponse response) {
		log.debug("registration controller method : GET");
		UserRegistationCommand command = new UserRegistationCommand();
		//command.setUserGender(0);
		
		model.addAttribute("userRegistationCommand", command);
		
		return "Registration"; 
		
	}
	
	@RequestMapping(method=RequestMethod.POST, value="/registration")
	public String registrationSubmit(@Valid UserRegistationCommand command, 
										BindingResult result,
										Model model, 
										HttpServletRequest request) {
		
		log.debug("registration controller method : POST");
		if (result.hasErrors()) {
            //show error on the form
            model.addAttribute("userRegistationCommand", command);
            log.debug("Has validation errors.");
            return "Registration";
        } else {
        	
        	User user = new User();
    		user.setUserAge(command.getUserAge());
    		user.setUserGender(command.getUserGender());
    		user.setUserInfo("");
    		user.setUserNickName(command.getUserNickName());
    		user.setUserPassword(command.getUserPassword());
    		user.setUserStatus(0);
    		
    		userDao.registerUser(user); 
    		
    		log.debug("new user registered id [" + user.getId() + "]");
    		request.getSession().setAttribute("currentUserId", user.getId());
    		
    		return "redirect:/main";         	
        }
		
	}
	
	@ModelAttribute("gender")
	public Map<String,String> populateGenderMap() {
 
		log.debug("populateGenderMap called");
		//Data referencing for web framework select
		Map<String,String> gender = new LinkedHashMap<String,String>();
		gender.put("0", "Male");
		gender.put("1", "Female");
		
		return gender;
	}
	
	
}
